package com.dminvoicemanager;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class DM_InvoiceMainActivity extends Activity {
	private String DBNAME = "dminvoicemanager.db";
	private String TEMP_USER = "invtempuser";
	private String TEMP_REP_INVOICESUMERY = "frepInvoiceSumery";
	private String ITEM_AREA = "fArea";
	private String ITEM_COMPANY_SETTING = "fCompanySetting";
	private String ITEM_CONTROL = "fControl";
	private String ITEM_DEBTOR = "fDebtor";
	private String ITEM_LOC_DETAILS = "fItemLoc";
	private String ITEM_LOCATION = "fLocation";
	private String ITEM_PRICE = "fItemPri";
	private String ITEMS = "fItems";
	private String INV_DETAILS = "FinvDet";
	private String INV_HEADER = "FinvHed";
	private String INV_NUMBER = "InvNumber";
	private String INV_SAL_REP = "fSalRep";
	private SQLiteDatabase mydb;
	String RepInvCode, TransTypePrefix, AgentPrefixType, LatestInvNumber,
			LatestInvState, ActiveInvoice, RepPrefixCode, RepLocationCode,
			username, userpass;
	EditText ETusername, ETpassword;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_invoice_main_activity);

		ETusername = (EditText) findViewById(R.id.repuname);
		ETpassword = (EditText) findViewById(R.id.reppsswd);

		Button userLogin = (Button) findViewById(R.id.userloginbutton);
		userLogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				if (ETusername.length() != 0 && ETpassword.length() != 0) {
					username = ETusername.getText().toString();
					userpass = ETpassword.getText().toString();
					authenticateuser(username.toUpperCase(),
							userpass.toUpperCase());
				} else {
					final AlertDialog alertDialog = new AlertDialog.Builder(
							DM_InvoiceMainActivity.this).create();
					// Setting Dialog Title
					alertDialog.setTitle("Invalid Login");
					// Setting Dialog Message
					alertDialog.setMessage("Enter User Name & Password");
					// Setting Icon to Dialog
					alertDialog.setIcon(R.drawable.warning);
					// Setting OK Button
					alertDialog.setButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									alertDialog.dismiss();
								}
							});
					// Showing Alert Message
					alertDialog.show();
				}
			}

		});

		Button quitall = (Button) findViewById(R.id.quitall);
		quitall.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				DM_InvoiceMainActivity.this.finish();
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());

			}

		});
		super.onDestroy();
	}

	private void authenticateuser(String username, String userpass) {
		SQLiteDatabase mydb = openOrCreateDatabase(DBNAME,
				Context.MODE_PRIVATE, null);
		Cursor replogincursor = null;
		String[] cols = { "RepCode", "RepTCode" };
		try {
			replogincursor = mydb.query(INV_SAL_REP, cols, "RepCode='"
					+ username + "' AND RepTCode='" + userpass + "'", null,
					null, null, null);
		} catch (Exception e) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			mydb.close();
			return;
		}
		if (replogincursor == null) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			mydb.close();
			return;

		}
		if (replogincursor.getCount() < 1) {
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Invalid User");
			// Setting Dialog Message
			alertDialog.setMessage("Invalid User Name & Password");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			replogincursor.close();
			mydb.close();
			return;
		}

		if (replogincursor.getCount() == 1) {
			/*
			 * Toast.makeText(getApplicationContext(), "Login success",
			 * 1).show();
			 */
			replogincursor.close();
			mydb.close();

			invoiceTransType();
			agentPrefix();
			repLocation();
			repPrefix();
			latestInvoiceRecord();
			// saveTempuserDeails();

			Intent myIntent = new Intent(this, DM_InvoiceMenu.class);
			startActivityForResult(myIntent, 0);
			finish();
			return;
		} else {
			replogincursor.close();
			mydb.close();
			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_InvoiceMainActivity.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("Login Error");
			// Setting Dialog Message
			alertDialog.setMessage("Error User Login");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();

		}

	}

	private void repLocation() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String currentUser = username.toUpperCase().trim();
		Cursor selectrepLocation = null;

		try {
			selectrepLocation = mydb.query(ITEM_LOCATION, null, "RepCode='"
					+ currentUser + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (selectrepLocation != null) {
			if (selectrepLocation.getCount() > 0) {
				while (selectrepLocation.moveToNext()) {
					String user = selectrepLocation.getString(13);
					RepLocationCode = selectrepLocation.getString(9);
				}
			} else {
				RepLocationCode = "LV002";
			}
		}

		selectrepLocation.close();
		mydb.close();
	}

	protected void saveTempuserDeails() {
		// TODO Auto-generated method stub
		RepInvCode = TransTypePrefix.trim() + AgentPrefixType.trim()
				+ RepPrefixCode;

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);

		try {
			ContentValues saveTempuserinvoice = new ContentValues();
			saveTempuserinvoice.put("repusername", ETusername.getText()
					.toString());
			saveTempuserinvoice.put("repprefix", RepPrefixCode);
			saveTempuserinvoice.put("tempRepInvNoCode", RepInvCode);
			saveTempuserinvoice.put("tempRepInvSerial", LatestInvNumber);
			saveTempuserinvoice.put("invoiceComplete", "0");
			saveTempuserinvoice.put("activeInvoice", ActiveInvoice);
			saveTempuserinvoice.put("activeInvoiceValue", "0");
			saveTempuserinvoice.put("activeInvItemDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscount", "0");
			saveTempuserinvoice.put("activeInvCusDiscountValue", "0");
			saveTempuserinvoice.put("InvoiceCustomerCode", "0");
			saveTempuserinvoice.put("InvoiceCustomerName", "0");
			saveTempuserinvoice.put("InvoiceSynchState", "0");
			saveTempuserinvoice.put("recordDate", getCurrentTimeString());
			saveTempuserinvoice.put("recordSynchDate", "0");
			saveTempuserinvoice.put("invlateststate", "9");
			saveTempuserinvoice.put("activeInvoiceReturnValue", "0");
			saveTempuserinvoice.put("activeInvoiceRemarks", "enter remarks");
			saveTempuserinvoice.put("invoiceNoOfItems", "0");
			saveTempuserinvoice.put("invoiceRef", "0");
			saveTempuserinvoice.put("invoiceRefStl", "");

			mydb.insert(TEMP_REP_INVOICESUMERY, null, saveTempuserinvoice);
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), "Error Occured..",
					Toast.LENGTH_SHORT).show();
		}

		mydb.close();
	}

	protected void latestInvoiceRecord() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		String[] selectstate = { "repusername", "invlateststate" };
		Cursor selectLastinvrec = null;
		try {
			selectLastinvrec = mydb.query(TEMP_REP_INVOICESUMERY, selectstate,
					"repusername='" + username + "' AND invlateststate='9'",
					null, null, null, null);
		} catch (Exception e) {
		}

		if (selectLastinvrec != null) {
			if (selectLastinvrec.getCount() > 0) {
				/*
				 * Toast.makeText(getApplicationContext(),
				 * "No Previous Invoice", Toast.LENGTH_SHORT).show();
				 */
			} else {
				LatestInvNumber = "1";
				LatestInvState = "0";
				ActiveInvoice = "1";
				saveTempuserDeails();
			}
		} else {
			Toast.makeText(getApplicationContext(), "No Active Invoice",
					Toast.LENGTH_SHORT).show();
		}
		/*
		 * if (selectLastinvrec != null) { if (selectLastinvrec.getCount() > 0)
		 * { while (selectLastinvrec.moveToNext()) { String LatestInvNumberStr =
		 * selectLastinvrec.getString(4); LatestInvState =
		 * selectLastinvrec.getString(5); // If // invoice // complete
		 * 
		 * Toast.makeText(getApplicationContext(),
		 * "LatestInvNumberStr :"+LatestInvNumberStr, Toast.LENGTH_SHORT)
		 * .show();
		 * 
		 * if (LatestInvState.equals(0)) {
		 * 
		 * Toast.makeText(getApplicationContext(), "Upcomming Invoice****",
		 * Toast.LENGTH_SHORT) .show();
		 * 
		 * // saveTempuserDeails(); } else if (LatestInvState.equals(1)) {
		 * 
		 * Toast.makeText(getApplicationContext(), "Incomplete Invoice****",
		 * Toast.LENGTH_SHORT) .show();
		 * 
		 * } else { Toast.makeText(getApplicationContext(), "New Invoice****" +
		 * LatestInvNumber, Toast.LENGTH_SHORT).show(); int preInvoiceNo =
		 * Integer.parseInt(LatestInvNumberStr); int newInvoiceNo = preInvoiceNo
		 * + 1; LatestInvNumber = String.valueOf(newInvoiceNo); ActiveInvoice =
		 * "1"; saveTempuserDeails(); }
		 * 
		 * 
		 * } } else { LatestInvNumber = "1"; LatestInvState = "0"; ActiveInvoice
		 * = "1"; saveTempuserDeails(); } } else { LatestInvNumber = "1";
		 * LatestInvState = "0"; ActiveInvoice = "1"; saveTempuserDeails(); }
		 */
		mydb.close();
	}

	protected void agentPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectAgentPreType = null;

		try {
			selectAgentPreType = mydb.query(ITEM_CONTROL, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectAgentPreType != null) {
			if (selectAgentPreType.getCount() > 0) {
				while (selectAgentPreType.moveToNext()) {
					AgentPrefixType = selectAgentPreType.getString(18);
				}

			}
		}
		mydb.close();
	}

	private void repPrefix() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectRepPrefix = null;

		try {

			selectRepPrefix = mydb.query(INV_SAL_REP, null, "RepCode ='"
					+ username.toUpperCase().trim() + "'", null, null, null,
					null);

		} catch (Exception e) {
		}
		if (selectRepPrefix != null) {
			if (selectRepPrefix.getCount() > 0) {
				while (selectRepPrefix.moveToNext()) {
					/*
					 * String currentRef = ETusername.getText().toString();
					 * String RepCode = selectRepPrefix.getString(5); if
					 * (currentRef.equals(RepCode)) {
					 */

					RepPrefixCode = selectRepPrefix.getString(6);

					mydb.execSQL("DROP TABLE IF EXISTS invtempuser");

					mydb.execSQL("create table if not exists "
							+ TEMP_USER
							+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null);");

					ContentValues user = new ContentValues();
					user.put("username", ETusername.getText().toString());
					user.put("lrepprefix", RepPrefixCode);
					user.put("lreploccode", RepLocationCode);
					user.put("currentStOrdNo", "0");
					mydb.insert(TEMP_USER, null, user);
					// }

				}

			}
		}
		mydb.close();
	}

	protected void invoiceTransType() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectTransType = null;

		try {
			selectTransType = mydb.query(ITEM_COMPANY_SETTING, null, null,
					null, null, null, null);
		} catch (Exception e) {
		}
		if (selectTransType != null) {
			if (selectTransType.getCount() > 0) {
				while (selectTransType.moveToNext()) {
					String cSettingsCode = selectTransType.getString(1);
					String cCharValue = selectTransType.getString(4);
					if (cSettingsCode.equals("SECINV")) {
						TransTypePrefix = cCharValue;
					}

				}
			}
		}
		mydb.close();
	}

	private String getCurrentTimeString() {
		Calendar c = Calendar.getInstance();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String formattedDate = df.format(c.getTime());
		return formattedDate;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.dm__invoice_main, menu);
		return true;
	}

}
